import { LifeCycles } from '@/ayaka'

/**
 * 房间地图管理
 */
export default class RoomMap {
    protected constructor() {
        throw new Error('RoomMap 不可被实例化！')
    }

    public static getMemory() {
        if (!Memory.roomMap) {
            Memory.roomMap = {}
        }
        return Memory.roomMap
    }

    /**
     * 返回指定房间的统计数据
     */
    public static getStats(roomName: string) {
        return RoomMap.getMemory()[roomName]
    }

    /**
     * 统计指定房间的数据
     */
    public static statRoom(room: Room) {
        const memory = RoomMap.getMemory()

        memory[room.name] = {
            owner: room.controller?.owner?.username || room.controller?.reservation?.username,
            type: room.controller?.owner ? 'owned' : room.controller?.reservation ? 'source' : 'neutral',
            time: Game.time,
            level: room.controller?.level || 0,
        }
    }

    /**
     * 清理过期数据
     */
    public static clear() {
        if (Game.time % 10000) return
        const memory = RoomMap.getMemory()
        const expireTime = Game.time - 20000

        for (const roomName of Object.keys(memory)) {
            if (memory[roomName]!.time < expireTime) delete memory[roomName]
        }
    }
}

export const clearRoomMap: LifeCycles = {
    tickEnd() {
        RoomMap.clear()
    },
}
